<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * list.php - manage email distribution lists, html form
 *
 * @package   block_email_list
 * @author    Brent Boghosian <brent.boghosian@remote-learner.net>
 * @copyright 2011 Remote Learner -http://www..remote-learner.net
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @uses $CFG
 * @uses $COURSE
 * @uses $DB
 * @uses $OUTPUT
 * @uses $PAGE
 * @uses $USER
 */
require_once('../../../config.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/list.class.php');

/**
 * Print a disappearing error message
 *
 * @param string $errorstr The error string
 * @return void
 * @uses $OUTPUT Draws a box
 */
function print_disappear_error($errorstr) {
    global $OUTPUT;

    echo "<div id=\"errorstr\">\n";
    echo $OUTPUT->box(get_string($errorstr, 'block_email_list'), 'errorbox');
    echo "</div>\n";
    // make error disapper in 15sec
    echo "<script type=\"text/javascript\">\n"
        ."// <![CDATA[\nwindow.setTimeout('clear_err();', 15000);\n// ]]>\n"
        ."</script>\n";
}

/**
 * Format the displayname checking to see if the user has permission to see fullname
 *
 * @param object  $user     The user to be displayed
 * @param boolean $hascapfn Whether the current user has the ability to see fullnames
 * @return string The display name
 */
function user_displayname($user, $hascapfn) {
    return fullname($user, $hascapfn) .' ('. $user->username. ')';
}

define('MAX_USERS_PER_PAGE', 500);

$contextid      = optional_param('contextid', 0, PARAM_INT); // context id
$add            = optional_param('add', 0, PARAM_BOOL);
$remove         = optional_param('remove', 0, PARAM_BOOL);
$delete         = optional_param('delete', 0, PARAM_BOOL);
$go             = optional_param('go', 0, PARAM_BOOL);
$showall        = optional_param('showall', 0, PARAM_BOOL);
$searchtext     = optional_param('searchtext', '', PARAM_RAW); // search string
$previoussearch = optional_param('previoussearch', 0, PARAM_BOOL);
$userid         = optional_param('userid', 0, PARAM_INT); // needed for user tabs
$courseid       = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
$listid         = optional_param('listid', 0, PARAM_INT);
$listname       = optional_param('listname', '', PARAM_RAW);

global $CFG, $COURSE, $DB, $OUTPUT, $PAGE, $USER;

$previoussearch = ($searchtext != '') or ($previoussearch) ? 1:0;

$contextlevel = CONTEXT_COURSE;

if ($courseid == SITEID) {
    $context = context_system::instance();
} else {
    $context = context_course::instance($courseid);
}

if ($context->contextlevel == CONTEXT_COURSE) {
    $courseid = $context->instanceid;

    if ( !($course = $DB->get_record('course', array('id' => $courseid)))) {
        error('Invalid course id');
    }

} else if (!empty($courseid)) { // we need this for user tabs in user context

    if (!$course = $DB->get_record('course', array('id' => $courseid))) {
        error('Invalid course id');
    }
} else {
    $courseid = SITEID;
    $course = clone($SITE);
}

require_login($courseid, false); // No autologin guest

require_capability('moodle/course:viewparticipants', $PAGE->context);

/// Get some language strings

$strpotentialusers = get_string('potentialusers', 'role');
$strexistingusers = get_string('existingusers', 'role');
$strsearch = get_string('search');
$strshowall = get_string('showall');
$strsearchresults = get_string('searchresults');

if (empty($userid)) {
    $userid = $USER->id;
}

if (has_capability('block/email_list:editsettings', $context)) {
    $preferencesbutton = email_get_preferences_button($courseid);
    $PAGE->set_button($preferencesbutton);
}
$stremail  = get_string('name', 'block_email_list');

// below for testing - should be commented out!
// if (empty($listid)) $listid = 1;

$PAGE->set_title("$course->shortname: $stremail");
$PAGE->set_heading($course->fullname);
$PAGE->set_cacheable(true);
$PAGE->set_url('/blocks/email_list/email/list.php?courseid='. $course->id);
$PAGE->navbar->add(get_string('nameplural', 'block_email_list'), 'index.php?id='.$course->id);
$PAGE->navbar->add(get_string('name', 'block_email_list'));
$PAGE->requires->css('/blocks/email_list/email/email.css');
$PAGE->requires->css('/blocks/email_list/email/treemenu.css');
$PAGE->requires->css('/blocks/email_list/email/tree.css');
$PAGE->requires->js('/blocks/email_list/email/treemenu.js');
$PAGE->requires->js('/blocks/email_list/email/email.js');

echo $OUTPUT->header();

// Include any required javascript code
$clear_err = <<<EOS
<script type="text/javascript">
// <![CDATA[
function clear_err() {
    document.getElementById('errorstr').innerHTML='';
}
// ]]>
</script>
EOS;
echo $clear_err;

/// Print the main part of the page

// Print principal table. This have 2 columns . . .  and possibility to add right column.
echo '<table id="layout-table">
                        <tr>';

// Print "blocks" of this account
echo '<td style="width: 180px;" id="left-column">';
email_printblocks($USER->id, $courseid);

// Close left column
echo '</td>';

// Print principal column
echo '<td id="middle-column">';

// Print middle table
echo $OUTPUT->heading(get_string('editlists', 'block_email_list'));

echo '<div>&#160;</div>';

// Print tabs options
email_print_tabs_options($courseid, 0);

if (! has_capability('block/email_list:createlist', $context)) {
    print_error('forbiddencreatelist', 'block_email_list');
}

$listobj = new maillist();
$listmembers = null;

if ( !empty($listid) ) {
    $listobj->id = $listid;

    if ($listobj->get_list_by_id($listid) == null) {
        print_error('listnotfound', 'block_email_list', '', $listid);
    }
}

/// Process incoming list selection submissions: select & new
if ($frm = data_submitted()) {
    //if (debugging('',DEBUG_DEVELOPER)) print_object($frm);

    // check if delete pressed
    if (!empty($listid) && !empty($delete)) {

        if ( $listobj->del_list() ) {
            $listid = 0;
        } else {
            print_disappear_error('faildeletelist');
        }
    }

    // check for listname and go button pressed
    if (!empty($listname) && !empty($go)) {
        $listname = trim($listname);
        // note: new_list will load existing list matching listname, userid

        if ( !empty($listname) ) {

            if ( empty($listid) ) {
                // create new list (or load existing list)
                $ret = $listobj->new_list($listname, $userid);

                if ($ret == 0 || !$listobj->id) {
                    // error creating list
                    print_error('failcreatelist', 'block_email_list', '', $listname);

                } else if ($ret == -1) {
                    print_disappear_error('cannotcreatelistexists');
                }
            } else {
                // rename existing list
                $ret = $listobj->edit_list($listname);

                if ($ret == -1) {
                    print_disappear_error('cannotrenamelistexists');

                } else if ($ret == 0) {
                    print_error('faileditlist', 'block_email_list', '', $listname);
                }
            }
            $listid = $listobj->id;
        } else {
            // invalid/empty listname
            print_disappear_error('invalidlistname');
        }
    }
}

// Output the list selector/creator form
echo "<form name=\"selectlist\" action=\"\" method=\"post\" >\n<center>";
echo '<fieldset class="clearfix" id="moodle"><legend class="ftoggler">'
    .get_string('list', 'block_email_list')."</legend>\n";
echo '<div class="fitemtitle"><label for="listid">'. get_string('selectlist', 'block_email_list');

// onchange should submit to reload dynamic form
$onchange = 'document.selectlist.submit();';

echo " </label><select name=\"listid\" id=\"listid\" onchange=\"{$onchange}\">\n"
    .'<option value="0"'. (!$listid ? ' selected="selected"': '')
    .'>'.get_string('newlist', 'block_email_list')."</option>\n";

$userlists = $DB->get_records('block_email_list_lists', array('owner' => $userid));

if (!empty($userlists)) {

    foreach ($userlists as $userlist) {
        echo "<option value=\"{$userlist->id}\""
            .(($listid == $userlist->id) ? ' selected="selected"': '')
            .">{$userlist->listname}</option>\n";
    }
}
echo '</select>';

// if not new list (listid > 0) output delete button
if ( !empty($listid) ) {
    $onclickdel = "if (confirm('".get_string('suredellist', 'block_email_list')
                . "') ) { document.getElementById('delete').value = 1; document.selectlist.submit(); }";
    echo "<input type=\"hidden\" name=\"delete\" id=\"delete\" value=\"0\"/>\n";
    echo '&nbsp;&nbsp;<input type="button" name="deletebtn" id="deletebtn" value="'
         .get_string('delete')."\" onclick=\"{$onclickdel}\"/>\n";
}
echo "</div><br />\n";

echo "\n<div class=\"fitemtitle\"><label for=\"id_name\">".get_string('enterlistname', 'block_email_list');
// text input field for listname
echo " <input name=\"listname\" id=\"listname\" type=\"text\" maxlength=\"255\" size=\"40\" value=\"\"/>\n";

// Submit(Go) button(s)
$onclickgo = "if (document.getElementById('listname').value == '') { alert('"
           .get_string('mustenterlistname', 'block_email_list')."'); return false;} return true;";
echo "<input type=\"submit\" name=\"go\" id=\"go\" onclick=\"{$onclickgo}\" value=\""
    .(!empty($listid) ? get_string('rename') : get_string('create'))."\" />\n";

echo "</fieldset>\n";
echo "</center></form><br />\n";

/// Process incoming list member changes
if ($frm) {

    if ($add and !empty($frm->addselect) and confirm_sesskey()) {

        foreach ($frm->addselect as $adduser) {

            if (!$adduser = clean_param($adduser, PARAM_INT)) {
                continue;
            }
            $ret = $listobj->add_member($adduser);

            if ($ret == 0) {
                print_error('failaddmember', 'block_email_list');
            }
        }

    } else if ($remove and !empty($frm->removeselect) and confirm_sesskey()) {

        foreach ($frm->removeselect as $removeuser) {

            if ( !$removeuser = clean_param($removeuser, PARAM_INT) ) {
                continue;
            }
            $listobj->del_member($removeuser);
        }

    } else if ($showall) {
        $searchtext = '';
        $previoussearch = 0;
    }
}

if (!empty($listid)) {
    $listmembers = $listobj->get_members();
    $numlistmembers = $listmembers ? count($listmembers) : 0;
    $studentrole = $DB->get_record('role', array('shortname' => 'student'));

    $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.email
                 FROM {user} u
                 JOIN {role_assignments} r ON u.id=r.userid
      LEFT OUTER JOIN {context} ctx ON r.contextid=ctx.id AND ctx.contextlevel = '.CONTEXT_COURSE.'
                WHERE u.username <> \'guest\' AND u.deleted = 0 AND u.confirmed = 1 AND ctx.instanceid = :courseid
                  AND u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :studentroleid AND contextid = :context)
                  AND u.id NOT IN (SELECT userid FROM {block_email_list_members} WHERE listid = :listid)
             ORDER BY username';
    $values = array('courseid' => $courseid, 'listid' => $listobj->id, 'studentroleid' => $studentrole->id, 'context' => $context->id);

    $searchtext = trim($searchtext);

    if ($searchtext !== '') {   // Search for a subset of remaining users
        $like      = $DB->sql_ilike();
        $fullname  = $DB->sql_fullname();
        $selectsql = " AND ($fullname $like :search OR username $like :search) ";
        $select  .= $selectsql;
        $values['search'] = "%$searchtext%";
    }


    $usercount = 0;

    if ($availableusers = $DB->get_records_sql($select, $values, 0, MAX_USERS_PER_PAGE)) {
        $usercount = is_array($availableusers) ? count($availableusers) : 1;
    }

    $hascapfullname = has_capability('moodle/site:viewfullnames', $context);

    ob_start();
    include('list.html');
    $html = ob_get_contents();
    ob_end_clean();

    // load 2nd form: edit list members
    echo $OUTPUT->box($html);

}

// Close principal column
echo '</td>';

// Close table
echo '</tr> </table>';

echo $OUTPUT->footer();
